jQuery(document).ready(function() {
    ////////////////////////
    //Variable definition///
    ////////////////////////
    //Style variables
    var windowHeight = 0;// The window height
    var windowWidth = 0;// The window width  
    var contentHeight = 0;// The content height  
    var leftWidth = 0;//
    var queryString;//Reference to queryString
    ////////////////////////
    ////jQuery selectors////
    ////////////////////////
    var leftPanel = jQuery("#left");  
    var rightPanel= jQuery("#right");  
    var toggler = jQuery("#toggler");  
    var tags = jQuery("#tags");  
    var tree = jQuery("#tree");  
    var queryInput = jQuery('#queryForm\\:queryString');
    ////////////////////////
    ///////Functions////////
    ////////////////////////
    //Calculte window dimensions
    function calculateDimensions(){  
        windowHeight = document.documentElement.clientHeight;
        windowWidth = document.documentElement.clientWidth;
        contentHeight = (windowHeight - 63 - 20)  +"px";  
    }  
    //Resize the panels
    function resizePanels(){  
        //Set the widths
        rightPanel.css("width",windowWidth-leftWidth);
        jQuery("#resultsTitle").css("width",windowWidth-leftWidth-20);
        //Set the heights
        tags.css("height", contentHeight-50 +"px");
        tree.css("height", contentHeight-50 +"px");
        tree.css("max-height",contentHeight-50 +"px");
        toggler.css("height", contentHeight);  
        jQuery("#browseContent").css("height",contentHeight);
        jQuery("#resultsList").css("max-height",contentHeight);
        jQuery("#infovis").css("height",contentHeight);
        
    }  
    //Show tags and hide tree
    function showTags(){  
        tags.show();  
        tree.hide();
        toggler.hide();
    }  
    //Show tree and hide tags
    function showTree(){  
        tags.hide();  
        tree.show();
        toggler.show();
    } 
    function initVisualization(){
        var subHierarchyJson = jQuery.parseJSON(jQuery('#infovisData').text());
        $.jstree._themes = "./content/css/";
        $("#infovis")
        // call `.jstree` with the options object
        .jstree({
            // the `plugins` array allows you to configure the active plugins on this instance
            //            "plugins" : ["themes","ui","checkbox","json_data","contextmenu"],
            "plugins" : ["themes","ui","checkbox","json_data"],
            // it makes sense to configure a plugin only if overriding the defaults
            // each plugin you have included can have its own config object
            "core" : {
                "initially_open" : [ "concept12" ]
            },
            "json_data" : {
                "data" : subHierarchyJson
            }
        //            "contextmenu" : {
        //                "items" : { // Could be a function that should return an object like this one
        //                    "add" : {
        //                        "separator_before"	: false,
        //                        "separator_after"	: true,
        //                        "label"	        : "Add to query",
        //                        "action"	        : function (obj) {
        //                            this.create(obj);
        //                        }
        //                    },
        //                    "remove" : {
        //                        "separator_before"	: false,
        //                        "separator_after"	: true,
        //                        "label"	        : "Remove from query",
        //                        "action"	        : function (obj) {
        //                            this.create(obj);
        //                        }
        //                    }
        //                }
        //            }

        })
        // EVENTS
        // each instance triggers its own events - to process those listen on the container
        // all events are in the `.jstree` namespace
        // so listen for `function_name`.`jstree` - you can function names from the docs
        .bind("loaded.jstree", function (event, data) {
            //                            alert("loaded");
            // you get two params - event & data - check the core docs for a detailed description
            });
        //                        $("#demo1").jstree("set_focus"); 
        // with the methods below you can call even private functions (prefixed with `_`)
        // 2) you can get the focused instance using `$.jstree._focused()`. 
        //setTimeout(function () { $.jstree._focused().select_node("#phtml_1"); }, 1000);
        // 3) you can use $.jstree._reference - just pass the container, a node inside it, or a selector
        //setTimeout(function () { $.jstree._reference("#phtml_1").close_node("#phtml_1"); }, 1500);
        // 4) when you are working with an event you can use a shortcut
        $("#infovis").bind("select_node.jstree", function (e, data) {
            // data.inst is the instance which triggered this event
            //data.inst.select_node("#phtml_2", true);
            alert(data.rslt.obj.attr("id")); 
        });
    // setTimeout(function () { $.jstree._reference("#phtml_1").open_node("#phtml_1"); }, 2500);
        
        
    }
    //Render the query string showing the added concepts
    function renderQueryString(){
        var tempQueryString="";
        jQuery.each( queryInput.data(),function(key, value) {
            if(value.charAt(0)=="+"){
                tempQueryString  += "KS:"+key+":"+value.substr(1)+"+";
            }
        });
        if(tempQueryString.length>0){
            queryInput.val(queryString+" | "+tempQueryString);
        }else{
            queryInput.val(queryString);
        }
    }
    //Render the results
    function renderResults(nodeId){
        var documentMap = spaceTree.graph.getNode(nodeId).data.documentMap;
        var documentMapTokens= documentMap.split(",");
        var resultsCount = 0;
        var documentCount  = 0;
        var tokenCount = 0;
        jQuery('.singleResult').each(function(index) {
            if(documentCount==documentMapTokens[tokenCount]){
                tokenCount++;
                documentCount = 0;
            }
            if(tokenCount%2==0){
                this.style.display = "block";
                resultsCount++;
            }else{
                this.style.display = "none";
            }
            documentCount++;
        });
        jQuery('#numResults').text(resultsCount+" ")  
    }
    //Build the tag clouds
//    function buildTagCloud(){
//        var queryTags = jQuery("#queryTags");
//        var resultsTags = jQuery("#resultsTags");
//        var surgeryTags = jQuery("#surgeryTags");
//        spaceTree.graph.eachNode(function(node) { 
//            var randomnumber=Math.floor(Math.random()*20)
//            if(node.data.nodeType=="I"){
//                indexNodesArray.push(node.id);
//                queryTags.append("<a id=\"tag"+node.id+"\" class=\"tagLabel\" href=\"#\" rel=\""+randomnumber+"\">"+node.data.term+"</a>");
//            }
//            if(node.data.nodeType=="E"){
//                expandedNodesArray.push(node.id);
//                resultsTags.append("<a id=\"tag"+node.id+"\" class=\"tagLabel\" href=\"#\" rel=\""+randomnumber+"\">"+node.data.term+"</a>");
//            }
//            if(node.data.nodeType=="S"){
//                surgeryNodesArray.push(node.id);
//                queryTags.append("<a id=\"tag"+node.id+"\" class=\"tagLabel\" href=\"#\" rel=\""+randomnumber+"\">"+node.data.term+"</a>");
//            }
//        });
//        jQuery(".tagLabel").click(function(){
//            var tagId = this.id.substr(3);
//            spaceTree.onClick(tagId);
//            renderResults(tagId);
//        //            showTree();
//        });
//        jQuery.fn.tagcloud.defaults = {
//            size: {
//                start: 8, 
//                end: 20, 
//                unit: 'pt'
//            },
//            color: {
//                start: '#3333FF', 
//                end: '#000033'
//            }
//        };
//        jQuery("#queryTags a").tagcloud();
//        jQuery("#resultsTags a").tagcloud();
//        jQuery("#surgeryTags a").tagcloud();
//    }
    ////////////////////////
    //Init data structures//
    ////////////////////////
    leftWidth = leftPanel.width()+1;//
    queryString = queryInput.val();
    ////////////////////////
    ///////Add handlers/////
    ////////////////////////
    queryInput.click(function() {
        queryInput.val("");
    });
    $(window).resize(function(){  
        calculateDimensions();  
        resizePanels();  
    }); 
    toggler.hover(showTags,null);  
    tags.hover(null, showTree)
    ////////////////////////
    /////Init application///
    ////////////////////////
    calculateDimensions();  
    resizePanels(); 
    showTree();  
    initVisualization();
//    buildTagCloud();
});